<?php

namespace App\Observers;

use Throwable;
use App\Support\Currency;
use App\Models\VrtsRecord;
use Illuminate\Support\Facades\DB;

class VrtsRecordObserver
{
    /**
     * @param  VrtsRecord  $vrtsRecord
     * @throws Throwable
     */
    public function created(VrtsRecord $vrtsRecord)
    {
        $func = function () use ($vrtsRecord) {
            if ($vrtsRecord->type == VrtsRecord::TYPE_TRANSFER) {
                $type = '转账';
            } else if ($vrtsRecord->type == VrtsRecord::TYPE_RECEIPT) {
                $type = '收款';
            } else {
                $type = '兑换'; // todo 这里还不确定
            }

            $vrtsRecord->records()->create([
                'type' => $type,
                'currency' => Currency::VRTS,
                'value' => $vrtsRecord->value,
                'user_id' => $vrtsRecord->user_id
            ]);

            if ($vrtsRecord->vrt_value) {
                $vrtsRecord->records()->create([
                    'type' => $type,
                    'currency' => Currency::VRT,
                    'value' => $vrtsRecord->vrt_value,
                    'user_id' => $vrtsRecord->user_id,
                ]);
            }
        };

        try {
            DB::transaction($func);
        } catch (Throwable $exception) {
            throw $exception;
        }
    }
}
